<template>
  <div class="dept-manage">
    <!-- 搜索视图 -->
    <el-card class="box-card">
      <el-form ref="form" :inline="true" :model="queryForm">
        <el-form-item label="部门名称" prop="deptName">
          <el-input placeholder="请输入部门名称" v-model="queryForm.deptName" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDeptList" size="default"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button ize="default" @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格 -->
    <el-card class="box-card" v-loading="loading">
      <el-form :inline="true" class="demo-form-inline action">
        <el-form-item>
          <el-button type="primary" @click="handleOpen" size="default"
            >创建</el-button
          >
        </el-form-item>
      </el-form>
      <el-table :data="deptList" row-key="_id" stripe>
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          v-bind="item"
        ></el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDel(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="action == 'create' ? '创建部门' : '编辑部门'"
  >
    <el-form
      label-width="120px"
      ref="dialogForm"
      :model="deptForm"
      :rules="rules"
    >
      <el-form-item label="上级部门:" prop="parentId">
        <el-cascader
          placeholder="请选择上级部门"
          v-model="deptForm.parentId"
          :props="{ checkStrickly: true, value: '_id', label: 'deptName' }"
          clearable
          :options="deptList"
          :show-all-levels="true"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="部门名称:" prop="deptName">
        <el-input v-model="deptForm.deptName"></el-input>
      </el-form-item>
      <el-form-item label="负责人:" prop="user">
        <el-select v-model="deptForm.userName" @change="handleUser">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="`${item.userId}/${item.userName}/${item.userEmail}`"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户邮箱:" prop="userEmail">
        <el-input v-model="deptForm.userEmail" :label-width="formLabelWidth" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit"> 确 认 </el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { onMounted, getCurrentInstance, ref, reactive } from 'vue'
//   获取Composition API 上下文对象
const { ctx } = getCurrentInstance()
// 获取全局挂载的属性
const { $api, $message } =
  getCurrentInstance().appContext.config.globalProperties
const loading = ref(true)
const deptList = ref([])
const deptForm = reactive({
  parentId: [null]
})
const userList = ref([])
// const pager = reactive({
//   pageNum: 1,
//   pageSize: 10
// })
const formLabelWidth = '140px'
// 查询表单对象
const queryForm = reactive({
  deptaName: ''
})
// 数据加载状态
// const loading = ref(true)
const dialogFormVisible = ref(false)
const action = ref('create')

onMounted(() => {
  getDeptList()
  getAllUserList()
})
// 获取部门列表数据
const getDeptList = async () => {
  try {
    const list = await $api.getDeptList(queryForm)
    deptList.value = list
    setTimeout(() => {
      loading.value = false
    }, 300)
  } catch (error) {
    console.error(error)
  }

  // setTimeout(() => {
  //   loading.value = false
  // }, 300)
}

// 获取所有用户列表
const getAllUserList = async () => {
  const res = await $api.getAllUserList()
  userList.value = res
  // console.log(userList.value)
  // console.log(res)
}

const handleUser = async (val) => {
  console.log(val)
  const [userId, userName, userEmail] = val.split('/')
  Object.assign(deptForm, { userId, userName, userEmail })
}

// 重置查询数据
const handleReset = (form) => {
  ctx.$refs[form].resetFields()
}

// 打开创建弹窗
const handleOpen = () => {
  action.value = 'create'
  dialogFormVisible.value = true
}

// 提交部门创建/编辑
const handleSubmit = () => {
  ctx.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      let params = { ...deptForm }
      params.action = action.value
      delete params.user
      await $api.deptOperate(params)
      $message.success('创建成功')
      dialogFormVisible.value = false
      handleReset('dialogForm')
      getDeptList()
    }
  })
}

// 编辑功能
const handleEdit = (row) => {
  console.log(row)
  action.value = 'edit'
  dialogFormVisible.value = true
  // 将scope的值复制给deptForm
  ctx.$nextTick(() => {
    Object.assign(deptForm, row, {
      user: `${row.userId}/${row.userName && row.userName}/${row.userEmail}`
    })
  })
}

// 删除功能
const handleDel = async (_id) => {
  await $api.deptOperate({ _id, action: 'delete' })
  $message.success('删除成功')
  getDeptList()
}

// 规则
const rules = reactive({
  parentId: [
    {
      required: true,
      message: '请选择上级部门',
      trigger: 'blur'
    }
  ],
  user: [
    {
      // required: true,
      message: '请选择负责人',
      trigger: 'blur'
    }
  ]
})

// 定义表格列数据
const columns = reactive([
  {
    label: '部门名称',
    prop: 'deptName'
  },
  {
    label: '负责人',
    prop: 'userName'
  },
  {
    label: '员工工号',
    prop: 'userId'
  },
  {
    label: '更新时间',
    prop: 'createTime'
  },
  {
    label: '创建时间',
    prop: 'createTime'
  }
])
</script>
